package io.renren.common.weixin;
import io.renren.common.utils.Md5Util;

import java.net.URLEncoder;
import java.util.*;

public class WxPayCreateSign {

	/**
	 * 微信支付签名算法sign
	 * @param parameters
	 * @return
	 */
	public static String createSign(SortedMap<String, String> parameters, String partnerKey) {

		List<Map.Entry<String, String>> paramList = new ArrayList<>(parameters.entrySet());

		// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
		Collections.sort(paramList, Comparator.comparing(Map.Entry::getKey));
		StringBuffer sb = new StringBuffer();

		for (Map.Entry<String, String> item : paramList) {
			if (item.getKey() != null || item.getKey() != "") {
				String key = item.getKey();
				String val = item.getValue();
				if (!(val == "" || val == null)) {
					sb.append(key + "=" + val + "&");
				}
			}
		}


	/*	Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}*/
		sb.append("key=" + partnerKey);
		String sign = Md5Util.md5(sb.toString()).toUpperCase();
		return sign;
	}

	/**
	  * @description: 参数安全过滤
	  * @auther: create by jieShao email:2609207540@qq.com
	  * @date 2019/11/6
	  * @param
	  * @return
	  */
	public static Map<String, String> paraFilter(Map<String, String> sArray) {
		Map<String, String> result = new HashMap<String, String>(sArray.size());
		if (sArray == null || sArray.size() <= 0) {
			return result;
		}
		for (String key : sArray.keySet()) {
			String value = sArray.get(key);
			if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
				continue;
			}
			result.put(key, value);
		}
		return result;
	}

	/**
	  * @description:  创建请求参数
	  * @auther: create by jieShao email:2609207540@qq.com
	  * @date 2019/11/6
	  * @param
	  * @return
	  */
	public static void buildPayParams(StringBuilder sb,Map<String, String> payParams,boolean encoding){
		List<String> keys = new ArrayList<String>(payParams.keySet());
		Collections.sort(keys);
		for(String key : keys){
			sb.append(key).append("=");
			if(encoding){
				sb.append(urlEncode(payParams.get(key)));
			}else{
				sb.append(payParams.get(key));
			}
			sb.append("&");
		}
		sb.setLength(sb.length() - 1);
	}

	public static String urlEncode(String str){
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (Throwable e) {
			return str;
		}
	}

	/**
	  * @description: 微信回调校验签名
	  * @auther: create by jieShao email:2609207540@qq.com
	  * @date 2019/11/8
	  * @param
	  * @return
	  */
	public static boolean checkSign(Map<String, String> resultMap,String key) {
		boolean result = false;
		//获取微信返回的签名
		String wxSign = resultMap.get("sign");
		//重新生成签名
		resultMap.remove("sign");
		SortedMap<String,String> sortedMap=new TreeMap<String,String>(resultMap);
		String newSign = createSign(sortedMap, key);
		if (wxSign.equalsIgnoreCase(newSign)){
			result = true;
		}

		return result;
	}
}
